package com.fling.block;

import java.util.ArrayList;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.fling.Constants;
import com.fling.Locator;
import com.fling.objects.Hero;
import com.fling.observer.Subject;

public class BlockHandler implements Constants {

	private ArrayList<BlockPattern> patterns;
	private ArrayList<BlockPattern> storedPatterns;
	private BlockPattern currentPattern;
	private BlockPattern deletedPattern;
	private float timer;
	private boolean random;
	private Hero hero;
	private Subject subject;

	public static float ADD_ROW_TIMER = 2f / Locator.getYGameSpeed();

	public BlockHandler(Hero hero, Subject subject) {
		patterns = new ArrayList<BlockPattern>();
		storedPatterns = new ArrayList<BlockPattern>();
		deletedPattern = null;
		currentPattern = null;
		random=false;
		this.hero=hero;
		this.subject=subject;
		timer = 0;
		buildPatterns();
	}

	public void buildPatterns() {
		BlockPattern pattern = null;
		for (int i = 0; i < STORED_ROWS; i++) {
			pattern = new BlockPattern(hero, subject);
			if (i % 2 == 0) {
				pattern.buildPattern();
			} else {
				pattern.buildRandomPattern();
			}
			storedPatterns.add(pattern);
		}
		currentPattern = storedPatterns.remove(0);
		patterns.add(currentPattern);
	}

	public void render(SpriteBatch sb) {
		for (BlockPattern b : patterns) {
			b.render(sb);
		}
	}

	// alternate between adding desgined patterns and n random rows or blocks
	public void update(float delta) {
		timer += delta * Locator.getOverallGameSpeed();
		// add a designed pattern
		if (timer > currentPattern.getPatternTimer() / (Locator.getYGameSpeed() / 2)) {
			// remove the next pattern and build a new one
			currentPattern = storedPatterns.remove(0);
			patterns.add(currentPattern);

			BlockPattern pattern = new BlockPattern(hero, subject);
			if (random) {
				pattern.buildRandomPattern();
			} else {
				pattern.buildPattern();
			}
			storedPatterns.add(pattern);
			timer = 0;
			random=!random;
		}

		for (BlockPattern b : patterns) {
			b.update(delta);
			if (b.isBelowScreen()) {
				deletedPattern = b;
			}
		}
		if (null != deletedPattern) {
			deletedPattern.delete();
			patterns.remove(deletedPattern);
			deletedPattern = null;
		}
	}

	public void delete() {
		for (BlockPattern b : patterns) {
			b.delete();
		}

		patterns.clear();
		timer = 0;
		currentPattern = storedPatterns.remove(0);
		patterns.add(currentPattern);
	}
	
	public void reset(){
		for (BlockPattern b : patterns) {
			b.delete();
		}

		patterns.clear();
		timer = 0;
		storedPatterns.clear();
		buildPatterns();
	}
}
